<?php
/**
 * Created by PhpStorm.
 * User: 刘翰文
 * Date: 2018/8/30
 * Time: 8:10
 */

namespace app\api\service;

require '../extend/WxPay/WxPay.Api.php';

use app\api\model\BuyerInfo;
use app\api\model\OrderDetail;
use app\api\model\OrderPay;
use WxPay\WxPayApi;
use WxPay\WxPayUnifiedOrder;
use WxPay\WxPayJsApiPay;
use app\exception\safeException;
use app\exception\payExceptions;
use think\Loader;

//Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');
//Loader::import('WxPay.WxPay',EXTEND_PATH,'.Config.Interface.php');
class PayService
{
    /*1、检查订单(同时加入总价)
     *2、获取openid
     *3、订单预支付
     *4、计算签名
     *5、返回数据
     */

    /**
     * 需要商户订单号以及总价（分）及OPENID
     */

    private $order_id;
    private $open_id;
    private $price;//分

    //统一下单，WxPayUnifiedOrder中out_trade_no、body、total_fee、trade_type必填

    public function pay($order_id,$openid,$price){
        $this->order_id=$order_id;
        $this->price = $price;
        //self::GetOpenId();
        $this->open_id = $openid;
        $result=self::PrePayOrder();
        $wxresult=self::getPayResult($result);
        OrderPay::create([
            'order_id' => $order_id,
            'out_trade_no' => $order_id,
            'prepay_id' => $wxresult['prepay_id']
        ]);
        //Order::update(['prepay_id'=>$wxresult['prepay_id']],['id'=>$this->order_id]);
        return  self::sign($wxresult);
        //return $wxresult;
    }



    public function GetOpenId(){
        $result = BuyerInfo::where(['id'=>$this->uid])->find();
        $this->open_id = $result['openid'];
    }

    public function PrePayOrder(){
        $paydata= new WxPayUnifiedOrder();

        $bodys = OrderDetail::where(['order_id' => $this->order_id])->with('product')->select();

        $body = "";

        for($i = 0 ;$i<sizeof($bodys);$i++){
            $body = $body.$bodys[$i]['product']['product_name'];
        }

        $paydata->SetOut_trade_no($this->order_id);
        $paydata->SetTrade_type('JSAPI');
        $paydata->SetTotal_fee($this->price);
        $paydata->SetBody($body);
        $paydata->SetOpenid($this->open_id);
        $paydata->SetNotify_url('https://ksphp.erhuotuzi.cn/pay/no');

        return $paydata;
    }

    public function getPayResult($paydata){
        $wxconfig= new WxPayConfig();
        $wxresult= WxPayApi::unifiedOrder($wxconfig,$paydata);

        /*if($wxresult['return_code'] != 'SUCCESS' || $wxresult['result_code'] !='SUCCESS'){
            throw new payExceptions(['msg'=>$wxresult]);
        }*/

        //Order::update(['prepay_id'=>$wxresult['prepay_id']],['id'=>$this->order_id]);

        return $wxresult;
    }

    public function sign($wxresult){
        $wxconfig=new WxPayConfig();
        $jsApiPayData = new WxPayJsApiPay();
        $jsApiPayData->SetAppid(config('wx.appid'));
        $jsApiPayData->SetTimeStamp((string)time());
        $rand = md5(time() . mt_rand(0, 1000));
        $jsApiPayData->SetNonceStr($rand);
        $jsApiPayData->SetPackage('prepay_id=' . $wxresult['prepay_id']);
        $jsApiPayData->SetSignType('MD5');
        $sign = $jsApiPayData->MakeSign($wxconfig);
        $rawValues = $jsApiPayData->GetValues();
        $rawValues['paySign'] = $sign;
        //unset($rawValues['appId']);
        //$wxresult['sign'] = $sign;
        return $rawValues;
    }
}